﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using MedicWeb.MedicService;

namespace MedicWeb.forms.Reports.Statistic
{
    public partial class Statistic : SessionPage
    {
        #region Nested type: InstitutionList

        [Serializable]
        public class InstitutionList
        {
            public int Id { get; set; }
            public string Title { get; set; }
        }

        #endregion

        #region Nested type: OrderList

        [Serializable]
        public class OrderList
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public DateTime Date { get; set; }
            public string Number { get; set; }
        }

        #endregion

        #region Nested type: SpecialityList

        [Serializable]
        public class SpecialityList
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }

        #endregion
        protected List<OrderList> AllOrders
        {
            get
            {
                if (ViewState["AllOrders"] == null)
                {
                    ViewState["AllOrders"] = PopulateOrderList();
                }
                return (List<OrderList>) ViewState["AllOrders"];
            }
            set { ViewState["AllOrders"] = value; }
        }

        protected List<OrderList> ReportOrders
        {
            get
            {
                if (ViewState["ReportOrders"] == null)
                {
                    ViewState["ReportOrders"] = new List<OrderList>();
                }
                return (List<OrderList>) ViewState["ReportOrders"];
            }
            set { ViewState["ReportOrders"] = value; }
        }


        protected List<SpecialityList> AllSpecialities
        {
            get
            {
                if (ViewState["AllSpecialities"] == null)
                {
                    ViewState["AllSpecialities"] = PopulateSpecialityList();
                }
                return (List<SpecialityList>) ViewState["AllSpecialities"];
            }
            set { ViewState["AllSpecialities"] = value; }
        }


        protected List<SpecialityList> ReportSpecialities
        {
            get
            {
                if (ViewState["ReportSpecialities"] == null)
                {
                    ViewState["ReportSpecialities"] = new List<SpecialityList>();
                }
                return (List<SpecialityList>) ViewState["ReportSpecialities"];
            }
            set { ViewState["ReportSpecialities"] = value; }
        }

        protected List<InstitutionList> AllInstitutions
        {
            get
            {
                if (ViewState["AllInstitutions"] == null)
                {
                    ViewState["AllInstitutions"] = PopulateInstitutionLists();
                }
                return (List<InstitutionList>) ViewState["AllInstitutions"];
            }
            set { ViewState["AllInstitutions"] = value; }
        }

        protected List<InstitutionList> ReportInstitutions
        {
            get
            {
                if (ViewState["ReportInstitutions"] == null)
                {
                    ViewState["ReportInstitutions"] = new List<InstitutionList>();
                }
                return (List<InstitutionList>) ViewState["ReportInstitutions"];
            }
            set { ViewState["ReportInstitutions"] = value; }
        }


        protected List<OrderList> PopulateOrderList()
        {
            var mc = new MainService();
            List<OrderList> result = (from order in mc.GetOrderListFull(GetSession(), false)
                                      select
                                          new OrderList
                                              {
                                                  Id = order.Id,
                                                  Date = order.Date,
                                                  Name = order.Content,
                                                  Number = order.Number
                                              }).ToList();

            return result;
        }


        protected List<SpecialityList> PopulateSpecialityList()
        {
            var mc = new MainService();
            List<SpecialityList> result = (from spec in mc.GetSpecialityList(GetSession(), true)
                                           select
                                               new SpecialityList
                                                   {
                                                       Id = spec.Id,
                                                       Name = spec.Title,
                                                   }).ToList();

            return result;
        }


        protected List<InstitutionList> PopulateInstitutionLists()
        {
            var mc = new MainService();
            List<InstitutionList> result = (from institution in mc.GetInstitutionList(GetSession(), false)
                                            select new InstitutionList
                                                       {
                                                           Id = institution.Id,
                                                           Title = institution.Title
                                                       }).ToList();

            return result;
        }

        private void ToggleCheckState(GridView gv, bool chackState)
        {
            foreach (GridViewRow row in gv.Rows)
            {
                var cb = row.FindControl("cb") as CheckBox;
                if (cb != null)
                {
                    cb.Checked = chackState;
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
            if (scriptManager != null && scriptManager.IsInAsyncPostBack)
            {
                var t = 1;
            }



            if (!IsPostBack)
            {
                OrderDateFrom.Text = DateTime.Today.AddYears(-1).ToShortDateString();
                OrderDateTill.Text = DateTime.Today.ToShortDateString();
                Bind();
                PopulateDDLs();
                
            }
        }

        protected void PopulateDDLs()
        {
            var mc = new MainService();
            Region[] regions = mc.GetRegionList(GetSession(), false);
            ddlRegion.DataSource = regions;
            ddlRegion.DataTextField = "Title";
            ddlRegion.DataValueField = "id";
            ddlRegion.DataBind();
            ddlRegion.Items.Insert(0, new ListItem("--Все--", "0"));

            Locality[] localities = mc.GetLocalityList(GetSession(), false);
            ddlLocality.DataSource = localities;
            ddlLocality.DataTextField = "Title";
            ddlLocality.DataValueField = "id";
            ddlLocality.DataBind();
            ddlLocality.Items.Insert(0, new ListItem("--Все--", "0"));
        }

        protected void Bind()
        {
            n1.DataSource = AllOrders;
            n1.DataBind();

            n2.DataSource = ReportOrders;
            n2.DataBind();

            n3.DataSource = AllSpecialities;
            n3.DataBind();

            n4.DataSource = ReportSpecialities;
            n4.DataBind();

            n5.DataSource = AllInstitutions;
            n5.DataBind();

            n6.DataSource = ReportInstitutions;
            n6.DataBind();
        }

        protected void btr_click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in n1.Rows)
            {
                var cb = row.FindControl("cb") as CheckBox;
                if (cb != null && cb.Checked)
                {
                    var hf = row.FindControl("hf") as HiddenField;
                    if (hf == null) return;
                    int id;
                    if (!Int32.TryParse(hf.Value, out id)) return;

                    List<OrderList> elements = AllOrders.Where(x => x.Id == id).ToList();
                    AllOrders = AllOrders.Where(x => x.Id != id).ToList();
                    ReportOrders.AddRange(elements);
                    ReportOrders = ReportOrders;
                }
            }
            Bind();
        }


        protected void btr2_click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in n3.Rows)
            {
                var cb = row.FindControl("cb") as CheckBox;
                if (cb != null && cb.Checked)
                {
                    var hf = row.FindControl("hf") as HiddenField;
                    if (hf == null) return;
                    int id;
                    if (!Int32.TryParse(hf.Value, out id)) return;

                    List<SpecialityList> elements = AllSpecialities.Where(x => x.Id == id).ToList();
                    AllSpecialities = AllSpecialities.Where(x => x.Id != id).ToList();
                    ReportSpecialities.AddRange(elements);
                    ReportSpecialities = ReportSpecialities;
                }
            }
            Bind();
        }

        protected void btr3_click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in n5.Rows)
            {
                var cb = row.FindControl("cb") as CheckBox;
                if (cb != null && cb.Checked)
                {
                    var hf = row.FindControl("hf") as HiddenField;
                    if (hf == null) return;
                    int id;
                    if (!Int32.TryParse(hf.Value, out id)) return;

                    List<InstitutionList> elements = AllInstitutions.Where(x => x.Id == id).ToList();
                    AllInstitutions = AllInstitutions.Where(x => x.Id != id).ToList();
                    ReportInstitutions.AddRange(elements);
                    ReportInstitutions = ReportInstitutions;
                }
            }
            Bind();
        }


        protected void btl_click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in n2.Rows)
            {
                var cb = row.FindControl("cb") as CheckBox;
                if (cb != null && cb.Checked)
                {
                    var hf = row.FindControl("hf") as HiddenField;
                    if (hf == null) return;
                    int id;
                    if (!Int32.TryParse(hf.Value, out id)) return;

                    List<OrderList> elements = ReportOrders.Where(x => x.Id == id).ToList();
                    ReportOrders = ReportOrders.Where(x => x.Id != id).ToList();
                    AllOrders.AddRange(elements);
                    AllOrders = AllOrders;
                }
            }
            Bind();
        }

        protected void btl2_click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in n4.Rows)
            {
                var cb = row.FindControl("cb") as CheckBox;
                if (cb != null && cb.Checked)
                {
                    var hf = row.FindControl("hf") as HiddenField;
                    if (hf == null) return;
                    int id;
                    if (!Int32.TryParse(hf.Value, out id)) return;

                    List<SpecialityList> elements = ReportSpecialities.Where(x => x.Id == id).ToList();
                    ReportSpecialities = ReportSpecialities.Where(x => x.Id != id).ToList();
                    AllSpecialities.AddRange(elements);
                    AllSpecialities = AllSpecialities;
                }
            }
            Bind();
        }

        protected void btl3_click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in n6.Rows)
            {
                var cb = row.FindControl("cb") as CheckBox;
                if (cb != null && cb.Checked)
                {
                    var hf = row.FindControl("hf") as HiddenField;
                    if (hf == null) return;
                    int id;
                    if (!Int32.TryParse(hf.Value, out id)) return;

                    List<InstitutionList> elements = ReportInstitutions.Where(x => x.Id == id).ToList();
                    ReportInstitutions = ReportInstitutions.Where(x => x.Id != id).ToList();
                    AllInstitutions.AddRange(elements);
                    AllInstitutions = AllInstitutions;
                }
            }
            Bind();
        }

        protected void CheckOrdersByDate()
        {
            ToggleCheckState(n1, false);

            if (OrderDateFrom.Text == string.Empty || OrderDateTill.Text == string.Empty)
            {
                return; // TODO Make Alert via script
            }
            DateTime datafrom;
            if (!DateTime.TryParse(OrderDateFrom.Text, out datafrom)) return; //TODO Alert via script
            DateTime datatill;
            if (!DateTime.TryParse(OrderDateTill.Text, out datatill)) return; //TODO Alert via script

            if (datafrom > datatill)
            {
                return; //TODO Alert via script
            }

            int[] elements = (AllOrders.Where(x => x.Date.CompareTo(datafrom) >= 0 & x.Date.CompareTo(datatill) <= 0)
                .Select(s => s.Id)).ToArray();

            foreach (GridViewRow row in n1.Rows)
            {
                var cb = row.FindControl("cb") as CheckBox;

                var hf = row.FindControl("hf") as HiddenField;
                if (hf == null) return;
                int id;
                if (!Int32.TryParse(hf.Value, out id)) return;

                if (elements.Contains(id) && cb != null)
                {
                    cb.Checked = true;
                }
            }
        }

        protected void hcb1_CheckedChanged(object sender, EventArgs e)
        {
            var cb = sender as CheckBox;
            ToggleCheckState(n1, cb.Checked);
        }

        protected void hcb2_CheckedChanged(object sender, EventArgs e)
        {
            var cb = sender as CheckBox;
            ToggleCheckState(n2, cb.Checked);
        }

        protected void hcb3_CheckedChanged(object sender, EventArgs e)
        {
            var cb = sender as CheckBox;
            ToggleCheckState(n3, cb.Checked);
        }


        protected void hcb4_CheckedChanged(object sender, EventArgs e)
        {
            var cb = sender as CheckBox;
            ToggleCheckState(n4, cb.Checked);
        }

        protected void hcb5_CheckedChanged(object sender, EventArgs e)
        {
            var cb = sender as CheckBox;
            ToggleCheckState(n5, cb.Checked);
        }

        protected void hcb6_CheckedChanged(object sender, EventArgs e)
        {
            var cb = sender as CheckBox;
            ToggleCheckState(n6, cb.Checked);
        }


        protected void Export()
        {
            //TODO add Alert if OrderList is Empty
            if (ReportOrders.Equals(null))
            {
                
                return;
            }
            int[] reportOrdersIds = ReportOrders.Select(ro => ro.Id).ToArray();
            int[] reportSpecialitiesIds = ReportSpecialities.Select(rs => rs.Id).ToArray();
            int[] reportInstitutionsIds = ReportInstitutions.Select(ri => ri.Id).ToArray();
            ReportOrders.Sort((x, y) => x.Date.CompareTo(y.Date));
            string reportDateFrom = ReportOrders.Last().Date.ToShortDateString();
            string reportDateTill = ReportOrders.First().Date.ToShortDateString();

            Session["roi"] = reportOrdersIds;
            Session["rsi"] = reportSpecialitiesIds;
            Session["rii"] = reportInstitutionsIds;
            Session["datefrom"] = reportDateFrom;
            Session["datetill"] = reportDateTill;


            if (cbRegion.Checked)
            {
                Response.Redirect(@"~\forms\Reports\Statistic\StatisticByRegion.aspx");
            }
            else
            {
                Response.Redirect(@"~\forms\Reports\Statistic\StatisticBySpeciality.aspx");
            }
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            Session["excel"] = false;
            Export();
            //Response.Write("<script>window.open('~forms\\Reports\\Statistic\\StatisticBySpeciality.aspx','_blank');</script>");
        }

        protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
        {
            Session["excel"] = true;
            Export();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            CheckOrdersByDate();
        }

        protected void ddlRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            var mc = new MainService();
            int id = Convert.ToInt32(ddlRegion.SelectedItem.Value);
            Locality[] localities;
            if (id == 0)
            {
                localities = mc.GetLocalityList(GetSession(), false).ToArray();
                ddlLocality.DataSource = localities;
                ddlLocality.DataTextField = "Title";
                ddlLocality.DataValueField = "id";
                ddlLocality.DataBind();
                ddlLocality.Items.Insert(0, new ListItem("--Все--", "0"));
                ddlLocality.SelectedIndex = 0;
                return;
            }

            localities = mc.GetLocalityList(GetSession(), false).Where(l => l.Region.Id == id).ToArray();
            ddlLocality.DataSource = localities;
            ddlLocality.DataTextField = "Title";
            ddlLocality.DataValueField = "id";
            ddlLocality.DataBind();
            ddlLocality.Items.Insert(0, new ListItem("--Все--", "0"));
        }

        protected void ddlLocality_SelectedIndexChanged(object sender, EventArgs e)
        {
            var mc = new MainService();
            int id = Convert.ToInt32(ddlLocality.SelectedItem.Value);
            List<InstitutionList> institutions;
            if (id == 0)
            {
                institutions = (from institution in mc.GetInstitutionList(GetSession(), false)
                                select new InstitutionList
                                           {
                                               Id = institution.Id,
                                               Title = institution.Title
                                           }).ToList();


                AllInstitutions = institutions;
                Bind();
                return;
            }

            institutions = (from institution in mc.GetInstitutionList(GetSession(), false)
                            where institution.Locality.Id == id
                            select new InstitutionList
                                       {
                                           Id = institution.Id,
                                           Title = institution.Title
                                       }).ToList();


            AllInstitutions = institutions;
            Bind();
        }

        protected void tbSpeciality_TextChanged(object sender, EventArgs e)
        {
            
             var mc = new MainService();
            var tb = sender as TextBox;
            string tmp = Convert.ToString(tb.Text).ToUpper();
            if (tmp.Length > 0)
            {
                List<SpecialityList> result = (from spec in mc.GetSpecialityList(GetSession(), true)
                                               where spec.Title.ToUpper().StartsWith(tmp)
                                               select
                                                   new SpecialityList
                                                       {
                                                           Id = spec.Id,
                                                           Name = spec.Title,
                                                       }).ToList();
                AllSpecialities = result;
                Bind();
            } 
        }

        
    }
}